import { useEffect, useRef, useState } from "react";
import AMapLoader from "@amap/amap-jsapi-loader";
import { useSelector } from "react-redux";

export default function MapContainer() {
    const endaddress = useSelector((state) => state.ditu.endaddress);
    const startaddress = useSelector((state) => state.ditu.startaddress);
    
    const mapRef = useRef(null);
    const markersRef = useRef([]);
    const polylineRef = useRef(null);
    const infoWindowRef = useRef(null);
    const amapRef = useRef(null);
    const [mapLoaded, setMapLoaded] = useState(false);

    // 初始化地图
    useEffect(() => {
        window._AMapSecurityConfig = {
            securityJsCode: "3ad0e856356bde0ae176f6d1056cb665",
        };

        AMapLoader.load({
            key: "5b16e102891bcb7c2554eaa54f701d09",
            version: "2.0",
            plugins: ["AMap.Scale", "AMap.GeometryUtil", "AMap.Driving"],
        })
        .then((AMap) => {
            amapRef.current = AMap;
            mapRef.current = new AMap.Map("container", {
                viewMode: "2D",
                zoom: 13,
                center: [116.397428, 39.90923],
                zoomEnable: true,
                animateEnable: true,
            });
            
            // 创建信息窗口实例
            infoWindowRef.current = new AMap.InfoWindow({
                offset: new AMap.Pixel(0, -30),
                closeWhenClickMap: true,
            });
            
            setMapLoaded(true);
        })
        .catch((e) => {
            console.error("地图加载失败:", e);
        });

        return () => {
            if (mapRef.current) {
                mapRef.current.destroy();
                mapRef.current = null;
            }
        };
    }, []);

    // 清除所有覆盖物
    const clearAllOverlays = () => {
        if (mapRef.current) {
            // 清除所有标记
            if (markersRef.current.length > 0) {
                mapRef.current.remove(markersRef.current);
                // 移除所有标记的事件监听
                markersRef.current.forEach(marker => {
                    marker.off('click');
                });
                markersRef.current = [];
            }
            
            // 清除路径
            if (polylineRef.current) {
                mapRef.current.remove(polylineRef.current);
                polylineRef.current = null;
            }
            
            // 关闭信息窗口
            if (infoWindowRef.current) {
                infoWindowRef.current.close();
            }
        }
    };

    // 路径规划函数
    const calculateRoute = (AMap, startCoords, endCoords) => {
        return new Promise((resolve, reject) => {
            const driving = new AMap.Driving({
                policy: AMap.DrivingPolicy.REAL_TRAFFIC,
                ferry: 1,
            });

            driving.search(
                new AMap.LngLat(startCoords[0], startCoords[1]),
                new AMap.LngLat(endCoords[0], endCoords[1]),
                (status, result) => {
                    if (status === 'complete') {
                        resolve(result);
                    } else {
                        reject(new Error('路径规划失败'));
                    }
                }
            );
        });
    };

    // 更新地图和路径
    useEffect(() => {
        if (!mapLoaded || !amapRef.current || !startaddress || !endaddress) {
            return;
        }

        const AMap = amapRef.current;
        
        const updateMap = async () => {
            try {
                // 先清除所有覆盖物
                clearAllOverlays();

                const startCoords = startaddress.split(',').map(coord => parseFloat(coord.trim()));
                const endCoords = endaddress.split(',').map(coord => parseFloat(coord.trim()));

                // 创建起点标记
                const startMarker = new AMap.Marker({
                    position: startCoords,
                    title: '起点',
                    icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
                    offset: new AMap.Pixel(-12, -12)
                });

                // 执行路径规划
                const result = await calculateRoute(AMap, startCoords, endCoords);
                
                if (result.routes && result.routes.length > 0) {
                    const route = result.routes[0];
                    const distance = (route.distance / 1000).toFixed(2);
                    const time = Math.ceil(route.time / 60);

                    // 创建终点标记
                    const endMarker = new AMap.Marker({
                        position: endCoords,
                        title: `终点 - ${distance}公里`,
                        content: createMarkerContent('终点', distance, time),
                        offset: new AMap.Pixel(-25, -50)
                    });

                    // 添加标记点击事件显示详细信息
                    endMarker.on('click', () => {
                        infoWindowRef.current.setContent(`
                            <div style="padding: 8px; min-width: 150px;">
                                <div style="font-weight: bold; margin-bottom: 5px;">路线信息</div>
                                <div>距离: ${distance} 公里</div>
                                <div>预计时间: ${time} 分钟</div>
                                <div style="color: #666; font-size: 12px; margin-top: 5px;">点击地图其他位置关闭</div>
                            </div>
                        `);
                        infoWindowRef.current.open(mapRef.current, endCoords);
                    });

                    markersRef.current = [startMarker, endMarker];
                    mapRef.current.add(markersRef.current);

                    // 创建路径
                    const polyline = new AMap.Polyline({
                        path: route.steps.flatMap(step => step.path),
                        strokeColor: "#3366FF",
                        strokeOpacity: 0.8,
                        strokeWeight: 6,
                        strokeStyle: "solid",
                    });

                    polylineRef.current = polyline;
                    mapRef.current.add(polyline);

                    // 自动显示信息窗口
                    setTimeout(() => {
                        infoWindowRef.current.setContent(`
                            <div style="padding: 8px; min-width: 150px;">
                                <div style="font-weight: bold; margin-bottom: 5px;">路线信息</div>
                                <div>距离: ${distance} 公里</div>
                                <div>预计时间: ${time} 分钟</div>
                            </div>
                        `);
                        infoWindowRef.current.open(mapRef.current, endCoords);
                        
                        // 调整地图视野
                        mapRef.current.setFitView([startMarker, endMarker, polyline], false, [60, 60, 60, 60], 14);
                    }, 500);
                }

            } catch (error) {
                console.error("更新地图失败:", error);
                fallbackToStraightLine(AMap, startaddress, endaddress);
            }
        };

        // 备选方案
        const fallbackToStraightLine = (AMap, start, end) => {
            try {
                // 先清除所有覆盖物
                clearAllOverlays();

                const startCoords = start.split(',').map(coord => parseFloat(coord.trim()));
                const endCoords = end.split(',').map(coord => parseFloat(coord.trim()));

                const distance = AMap.GeometryUtil.distance(startCoords, endCoords);
                const distanceKm = (distance / 1000).toFixed(2);

                // 创建标记
                const startMarker = new AMap.Marker({
                    position: startCoords,
                    title: '起点',
                    icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
                });

                const endMarker = new AMap.Marker({
                    position: endCoords,
                    title: `终点 - ${distanceKm}公里`,
                    content: createMarkerContent('终点', distanceKm, Math.ceil(distance / 500)),
                    offset: new AMap.Pixel(-25, -50)
                });

                markersRef.current = [startMarker, endMarker];
                mapRef.current.add(markersRef.current);

                const polyline = new AMap.Polyline({
                    path: [startCoords, endCoords],
                    strokeColor: "#FF6B6B",
                    strokeOpacity: 0.6,
                    strokeWeight: 4,
                    strokeStyle: "dashed",
                });

                polylineRef.current = polyline;
                mapRef.current.add(polyline);

            } catch (error) {
                console.error("备选方案也失败了:", error);
            }
        };

        // 创建自定义标记内容
        const createMarkerContent = (title, distance, time) => {
            return `
                <div style="
                    background: white;
                    border: 2px solid #3366FF;
                    border-radius: 20px;
                    padding: 8px 12px;
                    box-shadow: 0 2px 6px rgba(0,0,0,0.2);
                    font-size: 12px;
                    font-family: Arial, sans-serif;
                    white-space: nowrap;
                    position: relative;
                ">
                    <div style="font-weight: bold; color: #3366FF;">${title}</div>
                    <div style="color: #666;">${distance} km</div>
                    <div style="
                        position: absolute;
                        bottom: -8px;
                        left: 50%;
                        transform: translateX(-50%);
                        width: 0;
                        height: 0;
                        border-left: 6px solid transparent;
                        border-right: 6px solid transparent;
                        border-top: 8px solid #3366FF;
                    "></div>
                </div>
            `;
        };

        updateMap();
    }, [startaddress, endaddress, mapLoaded]);

    return (
        <div style={{ 
            width: '100%',
            height: '100%',
            position: 'relative'
        }}>
            <div
                id="container"
                style={{ 
                    width: '100%',
                    height: '100%'
                }}
            />
        </div>
    );
}